<!--
 * @Author: Wangtao
 * @Date: 2020-10-22 19:27:39
 * @LastEditors: Wangtao
 * @LastEditTime: 2021-04-17 16:40:19
-->
<template>
  <drawer-box>
    <template v-slot:content>
      <el-form
        class="m7-form"
        :label-position="labelPosition"
        :rules="rules"
        :model="formData"
        size="mini"
        ref="nodeForm"
      >
        <el-form-item label="节点名称" prop="name">
          <el-input v-model.trim="formData.name" size="mini"></el-input>
        </el-form-item>
        <el-form-item label="放音类型" prop="playType">
          <el-radio-group v-model="formData.playType">
            <el-radio label="voiceLibrary">语音库</el-radio>
            <el-radio label="tts">语音合成TTS</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="服务厂商" prop="engine" v-if="formData.playType === 'tts'">
          <el-select v-model="formData.engine" placeholder="请选择">
            <el-option v-for="item in engineList" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <div class="soundSettings" v-if="formData.playType === 'tts'">
          <el-form-item label="合成文本" prop="text" style="width: 100%">
            <template v-slot:label>
              <span class="var-box">
                <span>合成文本</span>
                <el-dropdown @command="changeReplaceVar" class="fr" v-model="formData.replaceVar" trigger="click">
                  <span class="el-dropdown-link"> 插入变量<i class="MC_iconfont MC_icon-fangxiang-xia-xian"></i> </span>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item command="'${customerNumber}'">主叫号码</el-dropdown-item>
                      <el-dropdown-item command="'${trunkNumber}'">被叫号码</el-dropdown-item>
                      <el-dropdown-item command="'${agentNumber}'">座席工号</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </span>
            </template>
            <el-input
              class="var-input"
              type="textarea"
              size="mini"
              show-word-limit
              maxlength="300"
              v-model.trim="formData.text"
              placeholder="请输入文本（支持SSML标签）"
            ></el-input>
          </el-form-item>
          <div class="block">
            <span class="demonstration">语速</span>
            <el-slider v-model="formData.speechRate"></el-slider>
          </div>
          <div class="block">
            <span class="demonstration">音调</span>
            <el-slider v-model="formData.pitchRate"></el-slider>
          </div>
          <div class="block">
            <span class="demonstration">音量</span>
            <el-slider v-model="formData.volume"></el-slider>
          </div>
          <div class="block">
            <el-form-item label="音色" prop="voiceName">
              <el-select-v2
                style="width: 188.5px"
                size="mini"
                v-model="formData.voiceName"
                :placeholder="'请选择音色'"
                filterable
                :multiple="false"
                :collapse-tags="false"
                :options="voiceList"
                :remote="true"
              >
              </el-select-v2>
            </el-form-item>
          </div>
          <div class="voice-pre-box">
            <el-button type="primary" @click="compositePreview" size="mini">
              <!-- <img
                v-if="compositeLoading"
                style="width: 14px; display: inline-block; vertical-align: bottom; margin-right: 4px"
                alt=""
              /> -->
              <span style="font-size: 14px" class="MC_iconfont MC_icon-guanli"></span>
              <span>合成预览</span>
            </el-button>
            <audio v-if="formData.previewRecordUrl" :src="formData.previewRecordUrl" :autoplay="false" controls></audio>
          </div>
        </div>
        <el-form-item class="voice" label="语音文件" prop="voice" v-if="formData.playType === 'voiceLibrary'">
          <template #label>
            <span class="jump-voice">
              <span>语音文件</span>
              <el-button type="primary" link @click="onJump">配置语音库</el-button>
            </span>
          </template>
          <div style="display: flex">
            <el-select-v2
              style="width: 487px"
              size="mini"
              v-model="formData.voice"
              :placeholder="'请选择语音文件'"
              filterable
              :multiple="false"
              :collapse-tags="false"
              :options="voiceLibraryList"
              :remote="true"
              value-key="id"
              :defaultProps="{ label: 'name', value: 'id' }"
            >
            </el-select-v2>
            <Audio
              :row="{
                url: currentVoice.fileUrl
              }"
              style="margin-left: 10px"
              v-if="currentVoice.fileUrl"
            />
          </div>
        </el-form-item>
        <el-form-item label="重播次数" prop="replayTimes">
          <el-input v-model="formData.replayTimes" type="number" size="mini">
            <template v-slot:append>次</template>
          </el-input>
        </el-form-item>
        <el-form-item label="重播间隔" prop="replayInterval">
          <el-input v-model="formData.replayInterval" type="number" size="mini">
            <template v-slot:append>秒</template>
          </el-input>
        </el-form-item>
        <el-form-item :label="item.label" prop="region" v-for="(item, index) in condition" :key="index">
          <el-select v-model="item.to" placeholder="请选择下一步节点" style="width: 100%" clearable filterable>
            <el-option
              v-for="(node, index) in nodeList"
              :label="node.data.name"
              :value="node.id"
              :key="index"
              v-show="!node.viewOnly && node.id !== currentData.id && node.id !== 'startNode'"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </template>
    <template v-slot:operation>
      <el-button @click="cancel" size="mini">取消</el-button>
      <el-button type="primary" @click="onSubmit" size="mini">确定</el-button>
    </template>
    <template v-slot:remove>
      <el-button @click="deleteNode" type="danger" :icon="Delete" size="mini">删除</el-button>
    </template>
  </drawer-box>
</template>

<script lang="ts" setup>
import drawerBox from '@/app/call-center/components/drawer-box.vue'
import { withDefaults, defineProps, ref, reactive } from 'vue'
import useNodeCommon from './use-node-common'
import { cloneDeep } from 'lodash'
import { Delete } from '@element-plus/icons-vue'
import ivr from '@/app/call-center/store/modules/ivr'
import Audio from '@/common/components/audio/audio-operate.vue'
import { useRouter } from 'vue-router'

type State = {
  compositeLoading: boolean
}
const IvrModule = ivr()
const nodeForm: any = ref(null)
const props = withDefaults(
  defineProps<{
    data: any
    currentNode: any
    save: (...arg: any) => void
    cancel: () => void
    delete: (...arg: any) => void
  }>(),
  {
    data: {},
    currentNode: {}
  }
)
const {
  currentVoice,
  nodeList,
  currentData,
  labelPosition,
  rules,
  formData,
  voiceLibraryList,
  condition,
  cancel,
  onSubmit,
  deleteNode
}: any = useNodeCommon({
  data: props.data,
  currentNode: props.currentNode,
  nodeForm,
  save: props.save,
  cancel: props.cancel,
  delete: props.delete
})

const state: State = reactive({
  compositeLoading: false
})
const engineList: any[] = [{ label: '阿里云', value: 'ali' }]
const voiceList: object[] = [
  { label: '思悦（温柔女声）', value: 'siyue' },
  { label: '小云（标准女声）', value: 'xiaoyun' },
  { label: '小刚（标准男声）', value: 'xiaogang' },
  { label: '若兮（温柔女生）', value: 'ruoxi' },
  { label: '思琪（温柔女生）', value: 'siqi' }
]
const router = useRouter()
const onJump = () => {
  router.push('/app/call_router/voice-library')
}
const changeReplaceVar = (replaceVar: string) => {
  formData.value.text = `${formData.value.text || ''}${replaceVar}`
}
const compositePreview = () => {
  if (state.compositeLoading) {
    // 合成中，再次请求跳出
    return false
  }
  nodeForm.value.validate((valid: any) => {
    if (valid) {
      const actionData = cloneDeep(formData.value)
      if (actionData.text) {
        actionData.text = actionData.text
          .replaceAll('${customerNumber}', '主叫号码')
          .replaceAll('${trunkNumber}', '被叫号码')
          .replaceAll('${agentNumber}', '座席工号') // eslint-disable-line no-template-curly-in-string
      }
      state.compositeLoading = true
      const data = { url: '/call/web/call/action/config/ivr/generate', method: 'POST', data: actionData }
      IvrModule.IvrCommonAction(data).then((res: any) => {
        if (res && res.success && res.data) {
          formData.value.previewRecordUrl = res.data.key || ''
        }
        state.compositeLoading = false
      })
    } else {
      return false
    }
  })
}
// eslint-disable-next-line no-undef
defineExpose({
  form: nodeForm
})
</script>

<style lang="stylus" scoped>
.el-dropdown-link
  cursor pointer
  color #409EFF
.soundSettings
  display flex
  flex-wrap wrap
  justify-content space-between
  .block
    width 48%
.audioProgress
  margin 0 10px 0
.var-input
  :deep(.el-textarea__inner)
    height 72px
.var-box
  display: inline-flex !important;
  justify-content: space-between !important;
  align-items: center;
  width: 96.8% !important;
  padding-left: 10px;
  color: rgba(0,0,0,0.6) !important;
  padding-left: 0;
  font-weight: 500 !important;
  position: relative;
  span
    padding-left 0 !important
    font-size 14px !important
    color: rgba(0,0,0,0.6) !important;
    font-size: 14px !important;
    font-weight: 500 !important;
  :deep(.el-dropdown-link)
    color #1e63f5 !important
    font-size: 14px !important;
    font-weight: 500 !important;
  :deep(.el-dropdown)
    position: relative;
    right: -20px;
.voice-pre-box
  width: 100%;
  margin: -4px 0px 16px;
  display: flex;
  align-items: center;
  justify-content: space-between;
.voice
  :deep(.el-form-item__label)
    padding-right 0
  // .MC_icon-qiyong-kaishi
  //   color: #d3dffd;
.jump-voice
  display: inline-flex !important;
  justify-content: space-between !important;
  align-items: center;
  width: 97.8% !important;
  padding-left: 10px;
  color: rgba(0,0,0,0.6) !important;
  padding-left: 0;
  font-weight: 500 !important;
  position: relative;

  span
    padding-left 0 !important
    font-size 14px !important
    color: rgba(0,0,0,0.6) !important;
    font-size: 14px !important;
    font-weight: 500 !important;
  :deep(.el-button span)
    color var(--mc-main-color) !important
    font-size: 14px !important;
    font-weight: 500 !important;
    position: relative;
    right: -2px;
</style>
